﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LPV_POS.Module;
using LPV_POS.In;
using LPV_POS.Baocao;
using LPV_POS.Baocao.Epson;
using LPV_POS.Baocao.Bixolon;
using CrystalDecisions.CrystalReports.Engine;
using System.Resources;
using System.Globalization;

namespace LPV_POS.mh_pos.mh_inbaocao
{
    public partial class frmBaoCao_NguyenVatLieu : DevExpress.XtraEditors.XtraForm
    {
        CultureInfo culture;

        #region "Muti language"

        private void SetLanguage_banhang(string cultureName)
        {
            try
            {
                culture = CultureInfo.CreateSpecificCulture(cultureName);
                ResourceManager rm = new ResourceManager("LPV_POS.Muti_language.MyResource", typeof(frmBaoCao_NguyenVatLieu).Assembly);
                label1.Text = rm.GetString("nguyenlieu", culture);
                label2.Text = rm.GetString("tonkhonguyenlieu", culture);
                label4.Text = rm.GetString("tungay", culture);
                label5.Text = rm.GetString("denngay", culture);
                btnIn.Text = rm.GetString("in", culture);
                btnThoat.Text = rm.GetString("thoat", culture);
                this.col_NVLName.Caption = rm.GetString("nguyenlieu", culture);
                this.col_DVT.Caption  = rm.GetString("dvt", culture);
                this.gridColumn1.Caption= rm.GetString("tondau", culture); 
                this.gridColumn2.Caption= rm.GetString("nhap", culture);
                this.gridColumn3.Caption= rm.GetString("xuat", culture);
                this.coL_Ton_Kho.Caption= rm.GetString("tonkho", culture);
               // lblVAT_Khong.Text = rm.GetString("khongvat", culture);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Note");
            }

        }

        #endregion

        public frmBaoCao_NguyenVatLieu()
        {
            InitializeComponent();
            culture = CultureInfo.CurrentCulture;
        }
        bool iLoadForm = false;
        private void frmBaoCao_NguyenVatLieu_Load(object sender, EventArgs e)
        {
            cpublic ocpublic = new cpublic();
            string str_lang = ocpublic.Registry_Get("mh_main_lang");
            if (str_lang == "")
                str_lang = "vi-VN";
            SetLanguage_banhang(str_lang);

            dateTimePicker1.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 1);
            dateTimePicker2.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);

            this.Cursor = Cursors.WaitCursor;
            this.ShowCombo();
            //this.ShowData();
            iLoadForm = true;
            this.Cursor = Cursors.Default;
            checkEdit1.Checked = false;
        }

        void ShowData()
        {
            this.Cursor = Cursors.WaitCursor;
            DataTable tb1 = null;
            if (checkEdit1.Checked)
            {//theo thang
                tb1 = new thuvien().SP_SelectDataTable("sp_DM_NGUYENLIEU",
                                                        new string[] { "@flag", "@thang_nam", "@ma_khohang", "@MANGUYENLIEU" },
                                                        new object[] { 5, dtpThangnam.Value, Variable.ma_khohang, cboNguyenLieu._GetselectedID() });
            }
            else
            {// tu ngay - den ngay
                Boolean bBAO_CAO_TRONG_NGAY = false;
                DateTime dthang_nam = dtpThangnam.Value;

                bBAO_CAO_TRONG_NGAY = dateTimePicker1.Value.ToString("dd/MM/yyyy") == dateTimePicker2.Value.ToString("dd/MM/yyyy");
                if (bBAO_CAO_TRONG_NGAY)
                    dthang_nam = dateTimePicker1.Value;

                tb1 = new thuvien().SP_SelectDataTable("sp_DM_NGUYENLIEU",
                                                        new string[] { "@flag", "@thang_nam", "@ma_khohang", "@MANGUYENLIEU", "@DATE_TUNGAY", "@DATE_DENNGAY", "@BAO_CAO_TRONG_NGAY" },
                                                        new object[] { 6, dthang_nam, Variable.ma_khohang, cboNguyenLieu._GetselectedID(), dateTimePicker1.Value, dateTimePicker2.Value, bBAO_CAO_TRONG_NGAY });
            }
            grdData.DataSource = tb1;
            this.Cursor = Cursors.Default;
        }
        void ShowCombo()
        {
            DataTable tb1 = new thuvien().SP_SelectDataTable("sp_DM_NGUYENLIEU", new string[] { "@flag" }, new object[] { 4 });
            cboNguyenLieu.Datasource = tb1;
            cboNguyenLieu._Init();
            cboNguyenLieu.SelectedIndex = 0;
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void cboNguyenLieu_SelectedIndexChanged(object sender, EventArgs e)
        {
        //    if (iLoadForm)
        //        this.ShowData();
        }

        private void dtpThangnam_ValueChanged(object sender, EventArgs e)
        {
            //if (iLoadForm)
            //    this.ShowData();
        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            //
            DataTable tb = (DataTable)grdData.DataSource;
            thuvien tv = new thuvien();
            DataTable tbBN = tv.SP_SelectDataTable("sp_DM_MAYIN_BIENNHAN", null, null);
            DataView dv = tbBN.DefaultView;
            dv.Sort = "COMNAME";
            int vitri = dv.Find(new object[] { "USB" });
            int vitri_bixolon = dv.Find(new object[] { "BIXOLON" });
            int vitri_bixolon_100 = dv.Find(new object[] { "BIXOLON100" });
            if (vitri > -1 || vitri_bixolon > -1 || vitri_bixolon_100 > -1)
            {
                    #region "bao cao ban tieng viet"
           

            string tencongty = "";
            string dienthoai = "";
            string diachi = "";
                
            Mod_header_report header_report = new Mod_header_report();

            DataTable tb_header = header_report.f_selectheaderreport();
            if (tb_header.Rows.Count > 0)
            {
                tencongty = tb_header.Rows[0]["HEADER"] + "";
                dienthoai = tb_header.Rows[0]["PHONE"] + "";
                diachi = tb_header.Rows[0]["ADDRESS"] + "";
            }
            //ton kho nguyen lieu
            ReportDocument rpt;
             if(vitri > -1)
                    rpt = new bc_khohangNL_in_VN();
             else
                 rpt = new bc_khohangNL_in_Bixolon();

            // bc_khohangNL_in_Bixolon rpt = new bc_khohangNL_in_Bixolon();

            CrystalDecisions.CrystalReports.Engine.TextObject str_tencongty;
            str_tencongty = (CrystalDecisions.CrystalReports.Engine.TextObject)rpt.ReportDefinition.ReportObjects["txt_tencongty"];
            str_tencongty.Text = tencongty;

            CrystalDecisions.CrystalReports.Engine.TextObject str_dienthoai;
            str_dienthoai = (CrystalDecisions.CrystalReports.Engine.TextObject)rpt.ReportDefinition.ReportObjects["txt_dienthoaicongty"];
            str_dienthoai.Text = dienthoai;

            CrystalDecisions.CrystalReports.Engine.TextObject str_diachi;
            str_diachi = (CrystalDecisions.CrystalReports.Engine.TextObject)rpt.ReportDefinition.ReportObjects["txt_diachicongty"];
            str_diachi.Text = diachi;           //txt_ngaythangnam

            CrystalDecisions.CrystalReports.Engine.TextObject str_baocaongay;
            str_baocaongay = (CrystalDecisions.CrystalReports.Engine.TextObject)rpt.ReportDefinition.ReportObjects["txt_tungaydenngay"];
            str_baocaongay.Text = Variable.str_tungay;           //txt_ngaythangnam


            CrystalDecisions.CrystalReports.Engine.TextObject str_ngayinbill;
            str_ngayinbill = (CrystalDecisions.CrystalReports.Engine.TextObject)rpt.ReportDefinition.ReportObjects["txt_ngaythangnam"];
            str_ngayinbill.Text = "In báo cáo ngày " + string.Format("{0:dd/MM/yyyy}", DateTime.Today);           //txt_ngaythangnam

            rpt.SetDataSource(tb);
            rpt.DataDefinition.FormulaFields["SAN_PHAM"].Text = "{dt_report.NVLName}" + "";
            rpt.DataDefinition.FormulaFields["TON_KHO_BAN_DAU"].Text = "{dt_report.Ton_Dau}" + "";
            rpt.DataDefinition.FormulaFields["NHAP_KHO"].Text = "{dt_report.Nhap}" + "";
            rpt.DataDefinition.FormulaFields["XUAT_KHO"].Text = "{dt_report.Xuat}" + "";
            rpt.DataDefinition.FormulaFields["TON_CUOI_KY"].Text = "{dt_report.Ton_kho}" + "";
            rpt.DataDefinition.FormulaFields["DVT"].Text = "{dt_report.DVT}" + "";

            #region "   PrinterDefault"
            System.Drawing.Printing.PrinterSettings cls = new System.Drawing.Printing.PrinterSettings();
            string sPrinterDefault = cls.PrinterName;
            rpt.PrintOptions.PrinterName = sPrinterDefault;
            #endregion
            if (new cpublic().Registry_Get("chkCrystalReport_Display") + "" == "True")
            {
                mh_View frm = new mh_View(rpt);
                frm.Show();
            }
            rpt.PrintToPrinter(0, true, 1, 100);
            rpt.Dispose();//-----Xóa file tmp rpt---07/07/2012
            #endregion
            }
            else
            {
                     #region "Bao cao may in Ellic"

            PrintCOMs oPrintCOMs = new PrintCOMs(PrintCOMs.Print_Type.Print_BILL);
            SerialPort_LPV[] aSerialPort_LPV = oPrintCOMs.Print_Start();
            try
            {
                string ston_dau = "";
                string snhap = "";
                string sxuat = "";
                string ston_cuoi = "";

                float iton_dau = 0;
                float inhap = 0;
                float ixuat = 0;
                float iton_cuoi = 0;
                //Boolean iIn = false;
                string sTenNVL="";
                string sDVT = "";
                cpublic ocpublic = new cpublic();
                foreach (SerialPort_LPV oSerialPort_LPV in aSerialPort_LPV)
                {
                    if (oSerialPort_LPV != null)
                    {
                        oPrintCOMs.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Double_Height, "TON KHO NGUYEN LIEU", "", "", "");
                        if (checkEdit1.Checked)
                            oPrintCOMs.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Small, dtpThangnam.Value.ToString("-- MM-yyyy --"), "", "", "");
                        else
                        {
                            if (dateTimePicker1.Value.ToString("dd/MM/yyyy") == dateTimePicker2.Value.ToString("dd/MM/yyyy"))
                                oPrintCOMs.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Small, dateTimePicker1.Value.ToString("-- dd-MM-yyyy --"), "", "", "");
                            else
                                oPrintCOMs.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Small, "Tu " + dateTimePicker1.Value.ToString("-- dd-MM-yyyy --") + "den " + dateTimePicker2.Value.ToString("-- dd-MM-yyyy --"), "", "", "");
                        }
                        oPrintCOMs.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Small, ' ', PrintCOMs.Fills.Fills1Row3);

                        oPrintCOMs.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Small, this.f_splitString6Column("NGUYEN LIEU", "TON DAU", "NHAP","XUAT", "TON KHO", "DVT"));
                        oPrintCOMs.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Small, '-', PrintCOMs.Fills.Fills_Full);

                        foreach (DataRow dr in tb.Select())
                        {
                            sTenNVL = ocpublic.RemoveSign4VietnameseString(dr["NVLName"] + "");
                            float.TryParse(dr["Ton_Dau"] + "", out iton_dau);
                            float.TryParse(dr["Nhap"] + "", out inhap);
                            float.TryParse(dr["Xuat"] + "", out ixuat);
                            float.TryParse(dr["Ton_Kho"] + "", out iton_cuoi);
                            ston_dau = this.Replace_Decimal(iton_dau.ToString("N4"));
                            snhap = this.Replace_Decimal(inhap.ToString("N4"));
                            sxuat = this.Replace_Decimal(ixuat.ToString("N4"));
                            ston_cuoi = this.Replace_Decimal(iton_cuoi.ToString("N4"));
                            sDVT = dr["DVT"] + "";
                            
                            string[] aTenNVL = ocpublic.splitString(sTenNVL, 20 - iton_dau.ToString("N4").Trim().Length);
                            oPrintCOMs.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Small, this.f_splitString6Column(aTenNVL[0], ston_dau, snhap, sxuat, ston_cuoi, dr["DVT"] + ""));
                            if (aTenNVL.Length > 1)
                                if (aTenNVL[1] != "")
                                    oPrintCOMs.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Small, aTenNVL[1]);
                        }
                        oPrintCOMs.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Small, '-',PrintCOMs.Fills.Fills_Full);
                        oPrintCOMs.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Small, "Ngay gio in "+DateTime.Now.ToString("dd/MM/yyyy HH:mm"));
                        oPrintCOMs.Print_Bottom(oSerialPort_LPV);
                        oPrintCOMs.Print_Close();
                        //iIn = true;
                    }
                }
                //if (!iIn)
                //    MessageBox_LPV.Show("Cấu hình máy in hóa đơn", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
            finally
            {
                oPrintCOMs.Print_Close();
            }

            #endregion
            }
          
        }


        #region "   f_splitString6Column"
        string f_splitString6Column(string a, string b, string c, string d, string e, string f)
        {//i1: 39; i2:17
            cpublic ocpublic = new cpublic();
            a = ocpublic.RemoveSign4VietnameseString(a);
            f = ocpublic.RemoveSign4VietnameseString(f);

            string str = "";
            str = a;
            str += new cpublic().Spacestring(20 - a.Length - b.Length);
            str += b;
            str += new cpublic().Spacestring(9 - c.Length);
            str += c;
            str += new cpublic().Spacestring(11 - d.Length);
            str += d;
            str += new cpublic().Spacestring(11 - e.Length);
            str += e;            
            str += new cpublic().Spacestring(5 - f.Length);
            str += f;

            return str;
        }
        string Replace_Decimal(string sNumber)
        {

            sNumber = sNumber.Trim().Replace(".0000", "");
            //string[] sn = sNumber.Split(new char[] { '.' });
            //if (sn.Length > 1)
            //{
            //    string sub1 = sn[1];
            //    sNumber = sn[0];
            //    if (new cpublic().IsNumeric(sub1))
            //        if (int.Parse(sub1) > 0)
            //        {
            //            while (sub1.LastIndexOf("0") > 0)
            //                sub1 = sub1.Substring(0, sub1.Length - 1);
            //            sNumber = sNumber + "." + int.Parse(sub1);
            //        }
            //}
            return sNumber;
        }
        #endregion

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            if (iLoadForm)
            {
                iLoadForm = false;
                if (dateTimePicker1.Value > dateTimePicker2.Value)
                    dateTimePicker2.Value = new DateTime(dateTimePicker1.Value.Year, dateTimePicker1.Value.Month, dateTimePicker1.Value.Day, 23, 59, 59);

                //this.ShowData();
                iLoadForm = true;
            }
        }

        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {
            if (iLoadForm)
            {
                iLoadForm = false;
                if (dateTimePicker1.Value > dateTimePicker2.Value)
                    dateTimePicker1.Value = new DateTime(dateTimePicker2.Value.Year, dateTimePicker2.Value.Month, dateTimePicker2.Value.Day, 0, 0, 1);

                //this.ShowData();
                iLoadForm = true;
            }
        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            if (iLoadForm)
            {
                dateTimePicker1.Enabled = !checkEdit1.Checked;
                dateTimePicker2.Enabled = !checkEdit1.Checked;
                //
                dtpThangnam.Enabled = checkEdit1.Checked;

                //this.ShowData();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog s = new SaveFileDialog();
            s.Filter += "*.xls|*.xls";
            if (dateTimePicker1.Value.ToString("") != dateTimePicker2.Value.ToString(""))
                s.FileName = "BC_NVL" + dateTimePicker1.Value.ToString("yyyyMMdd") + "_" + dateTimePicker2.Value.ToString("yyyyMMdd");
            else
                s.FileName = "NhapKho_NVL" + dateTimePicker1.Value.ToString("yyyyMMdd");
            if (s.ShowDialog() == DialogResult.OK)
            {
                string FN = s.FileName;
                grvData.ExportToExcelOld(FN);
                if (System.IO.File.Exists(FN))
                    System.Diagnostics.Process.Start(FN);
            }
        }

        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            if (iLoadForm)
            {
                iLoadForm = false;
                if (dateTimePicker1.Value > dateTimePicker2.Value)
                    dateTimePicker1.Value = new DateTime(dateTimePicker2.Value.Year, dateTimePicker2.Value.Month, dateTimePicker2.Value.Day, 0, 0, 1);

                this.ShowData();
                iLoadForm = true;
            }
        }   
    }
}